<template>
  <el-row :gutter="20">
    <!-- 左侧电影列表 -->
    <el-col :span="18">
      <!-- 你的电影列表内容（不变） -->
      <el-row :gutter="20">
        <el-col :span="12" v-for="movie in movieList" :key="movie.id">
          <div class="movie-card" @click="goToMovieDetail(movie.id)">
            <img :src="movie.poster" class="movie-poster" alt="海报"/>
            <div class="movie-info">
              <div class="movie-title">{{ movie.title }}</div>
              <div class="movie-meta">
                {{ movie.year }} / {{ movie.genre }} / {{ movie.director }} / {{ movie.actors }}
              </div>
              <div class="movie-score">
                <el-rate
                    v-model="movie.starScore"
                    :max="5"
                    :allow-half="true"
                    disabled
                    :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                    :low-threshold="2"
                    :high-threshold="4"
                />
                <span class="score-text">{{ movie.score }} 分</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
      <div v-if="loading" style="text-align:center;margin:20px 0;">加载中...</div>
      <div v-if="finished" style="text-align:center;margin:20px 0;">已全部加载</div>
    </el-col>

    <!-- 右侧筛选栏 -->
    <el-col :span="6">
      <div class="sidebar-filter">
        <!-- 分类标签 -->
        <div class="category-list">
          <div
              v-for="cat in categories"
              :key="cat.value"
              :class="['category-item', {active: filter.category === cat.value}]"
              @click="selectCategory(cat.value)"
          >
            {{ cat.label }}
          </div>
        </div>
        <el-divider/>
        <!-- 下拉筛选 -->
        <div class="filter-bar">
          <div
              class="filter-item"
              :class="{active: activeFilter === 'genre'}"
              @click="toggleFilter('genre')"
          >
            类型 <span class="arrow"/>
          </div>
          <div
              class="filter-item"
              :class="{active: activeFilter === 'year'}"
              @click="toggleFilter('year')"
          >
            年代 <span class="arrow"/>
          </div>
          <div
              class="filter-item"
              :class="{active: activeFilter === 'sort'}"
              @click="toggleFilter('sort')"
          >
            排序 <span class="arrow"/>
          </div>
        </div>

        <!-- 弹出面板 -->
        <div v-if="activeFilter === 'genre'" class="filter-panel">
          <div
              v-for="g in genreOptions"
              :key="g"
              class="filter-option"
              :class="{selected: filter.genre === g}"
              @click="selectGenre(g)"
          >{{ g }}
          </div>
        </div>
        <div v-if="activeFilter === 'year'" class="filter-panel">
          <div
              v-for="y in yearOptions"
              :key="y"
              class="filter-option"
              :class="{selected: filter.year === y}"
              @click="selectYear(y)"
          >{{ y }}
          </div>
        </div>
        <div v-if="activeFilter === 'sort'" class="filter-panel">
          <div
              v-for="s in sortOptions"
              :key="s.value"
              class="filter-option"
              :class="{selected: filter.sort === s.value}"
              @click="selectSort(s.value)"
          >{{ s.label }}
          </div>
        </div>
      </div>
    </el-col>
  </el-row>
</template>

<script>
import {listMovie} from "@/api/movie/movie.js"

export default {
  name: 'Movie',
  data() {
    return {
      loading: false,
      movieList: [],
      pageNum: 1,
      pageSize: 10,
      finished: false,
      queryParams: {
        title: null,
        director: null,
        actors: null,
        duration: null
      },
      categories: [
        {label: '全部', value: ''},
        {label: '热门电影', value: 'hot'},
        {label: '最新电影', value: 'new'},
        {label: '豆酱高分', value: 'high'},
        {label: '冷门佳片', value: 'underrated'}
      ],
      filter: {
        category: '',
        genre: '',
        year: '',
        sort: ''
      },
      genreOptions: ['全部','儿童', '动画', '喜剧', '家庭', '传记', '纪录片', '悬疑', '剧情', '奇幻', '动作', '战争', '爱情', '运动',
        '灾难', '古装', '歌舞', '犯罪', '惊悚', '同性', '情色', '冒险', '科幻', '历史', '音乐', '西部', '华语'],
      yearOptions: ['全部','2025', '2024', '2023', '2022', '2021', '2020', '2010s', '2000s', '90s', '80s', '更早'],
      activeFilter: null, // 当前展开的筛选项
      sortOptions: [
        {label: '综合排序', value: ''},
        {label: '评分最高', value: 'score'},
        {label: '最新上映', value: 'releaseDate'}
      ],
    }
  },
  created() {
    this.getList();
    window.addEventListener('scroll', this.handleScroll);
    document.addEventListener('click', this.handleClickOutside);
  },
  beforeUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
    document.removeEventListener('click', this.handleClickOutside);
  },
  methods: {
    getList() {
      if (this.loading || this.finished) return;
      this.loading = true;
      const params = {
        ...this.queryParams,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ...this.filter
      };
      listMovie(params).then(res => {
        console.log(params);
        if (res.data && res.data.rows) {
          const rows = res.data.rows.map(movie => {
            if (movie.poster && movie.poster.startsWith('http')) {
              movie.poster = `https://images.weserv.nl/?url=${movie.poster.replace(/^https?:\/\//, '')}`;
            }
            movie.starScore = movie.score / 2;
            return movie;
          });
          this.movieList = [...this.movieList, ...rows];
          if (rows.length < this.pageSize) {
            this.finished = true;
          } else {
            this.pageNum++;
          }
        }
        this.loading = false;
      }).catch(error => {
        console.error('获取电影列表失败:', error);
        this.loading = false;
      });
    },
    handleScroll() {
      const scrollTop = window.scrollY || document.documentElement.scrollTop;
      const windowHeight = window.innerHeight;
      const docHeight = document.documentElement.scrollHeight;
      if (scrollTop + windowHeight + 100 >= docHeight) {
        this.getList();
      }
    },
    selectCategory(val) {
      this.filter.category = val;
      this.resetAndFetch();
    },
    resetAndFetch() {
      this.pageNum = 1;
      this.movieList = [];
      this.finished = false;
      this.getList();
    },
    toggleFilter(type) {
      this.activeFilter = this.activeFilter === type ? null : type;
    },
    selectGenre(g) {
      if (g === '全部')
        this.filter.genre = '';
      else
        this.filter.genre = g;
      this.activeFilter = null;
      this.resetAndFetch();
    },
    selectYear(y) {
      if (y === '全部')
        this.filter.year = '';
      else
        this.filter.year = y;
      this.activeFilter = null;
      this.resetAndFetch();
    },
    selectSort(val) {
      this.filter.sort = val;
      this.activeFilter = null;
      this.resetAndFetch();
    },
    handleClickOutside(e) {
      // 判断点击是否在筛选区域内
      if (!this.$el.querySelector('.filter-bar').contains(e.target) &&
          !this.$el.querySelector('.filter-panel')?.contains(e.target)) {
        this.activeFilter = null;
      }
    },
    goToMovieDetail(movieId) {
      console.log('跳转到电影详情页面，电影ID:', movieId);
      try {
        this.$router.push({
          path: `/movie/${movieId}`,
          query: { from: 'movies' }
        });
      } catch (error) {
        console.error('跳转失败:', error);
        // 如果路由跳转失败，尝试使用window.location
        window.location.href = `/movie/${movieId}?from=movies`;
      }
    }
  },
}
</script>

<style scoped>
.movie-card {
  display: flex;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
  padding: 16px;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.movie-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.movie-poster {
  width: 120px;
  height: 170px;
  object-fit: cover;
  border-radius: 8px;
  margin-right: 20px;
}

.movie-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 170px;
}

.movie-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}

.movie-meta {
  color: #666;
  font-size: 14px;
  margin-bottom: 12px;
}

.movie-score {
  display: flex;
  align-items: center;
  margin-top: 8px;
}

.score-text {
  margin-left: 10px;
  color: #F7BA2A;
  font-weight: bold;
}

.sidebar-filter {
  position: sticky;
  top: 30px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 24px 16px;
  z-index: 10;
}

.category-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
}

.category-item {
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background 0.2s, color 0.2s;
  outline: none;
}
.category-item.active, .category-item:hover {
  background: #f5f7fa;
  color: #409EFF;
  font-weight: bold;
}

.filter-bar {
  display: flex;
  gap: 24px;
  margin-bottom: 12px;
  justify-content: flex-start;
}

.filter-item {
  cursor: pointer;
  padding: 8px 18px;
  color: #333;
  font-weight: 500;
  background: none;
  border: none;
  border-radius: 0;
  transition: color 0.2s;
  outline: none;
}
.filter-item.active, .filter-item:hover {
  color: #409EFF;
}

.arrow {
  margin-left: 4px;
}

.filter-panel {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 16px;
  margin-top: 8px;
}

.filter-option {
  min-width: 60px;
  padding: 8px 12px;
  border: 1.5px solid #e0e7ef;
  border-radius: 6px;
  background: #fff;
  cursor: pointer;
  text-align: center;
  font-size: 14px;
  transition: all 0.2s;
  box-sizing: border-box;
  outline: none;
}
.filter-option.selected, .filter-option:hover {
  border-color: #409EFF;
  background: #e6f0ff;
  color: #409EFF;
  font-weight: bold;
}

*:focus {
  outline: none !important;
  box-shadow: none !important;
}
</style>